package it.illumedellaragione.googlecalendar;

import com.google.gdata.client.*;
import com.google.gdata.client.calendar.*;
import com.google.gdata.data.*;
import com.google.gdata.data.acl.*;
import com.google.gdata.data.calendar.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.Vector;

public class ManageGoogleCalendarV3 {

    //final String OWN_CALENDARS = "https://www.google.com/calendar/feeds/default/owncalendars/full";
    String user = "xxx";
    String pwd = "xxx";

    public ManageGoogleCalendarV3() {
    }

    public void start() {

        try {

            CalendarService myService = retrieveService(user, pwd);

            printAllCalendars(myService);
            //if(true) return;
            //createNewCalendar(myService);

            //printAllEvents(myService,user);


            // This is how to initialize a well-known Date (often used in unit test fixtures)
            DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //dfm.setTimeZone(TimeZone.getTimeZone("Europe/Zurich"));
            Date dataInizio = dfm.parse("2011-11-05 16:28:00");
            Date dataFine = dfm.parse("2011-11-05 17:28:00");


            //creo 3 anni (156)
            for (int i = 0; i < 2; i++) {

                String dataInizioString = (dfm.format(dataInizio) + "-00:00").replace(' ', 'T');
                String dataFineString = (dfm.format(dataFine) + "-00:00").replace(' ', 'T');
                ;
                DateTime startTime = DateTime.parseDateTime(dataInizioString);
                DateTime endTime = DateTime.parseDateTime(dataFineString);


                // output is likewise simple
                //System.out.println("Result: "+ dataInizioString);
                //System.out.println("Result: "+ test);
                //System.out.println(test.equals(dataInizioString));


                System.out.println("StartTime: " + startTime.toString());
                System.out.println("EndTime: " + startTime.toString());

                createEvent(myService, user, startTime, endTime);

                dataInizio = ManageDate.nextDate(dataInizio, "WEEKS", 1);
                dataFine = ManageDate.nextDate(dataFine, "WEEKS", 1);

            }


            /*
            for (int i = 0; i<2 ; i++){

            //Date dataInizio = new Date ("2011","11","06",oraInizio,minutiInizio);

            DateTime startDate;
            DateTime endDate;

            //createEvent(myService,user, DateTime startDate, DateTime endDate);

            }
             */
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public CalendarService retrieveService(String user, String password) throws AuthenticationException {

        // Create a CalenderService and authenticate
        CalendarService myService = new CalendarService("");
        myService.setUserCredentials(user, password);
        return myService;
    }

    private void printAllCalendars(CalendarService myService) throws IOException, ServiceException {

        // Send the request and print the response
        URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/allcalendars/full");

        //URL entryUrl = new URL("http://www.google.com/calendar/feeds/default/calendars/com.google.gdata.data.Link@87c268");

        CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);

        //CalendarEntry calendar= myService.getEntry(entryUrl, CalendarEntry.class);
        //System.out.println("\t" + calendar.getTitle().getPlainText());

        System.out.println("Your calendars:");
        System.out.println();
        for (int i = 0; i < resultFeed.getEntries().size(); i++) {
            CalendarEntry entry = resultFeed.getEntries().get(i);
            System.out.println("\t" + entry.getTitle().getPlainText());
            System.out.println("\t" + entry.getEditLink());
            System.out.println("\t" + entry.getId());
        }

    }

    public String printPublicAllCalendars(CalendarService myService) throws IOException, ServiceException {

        String ritorno = "";
        // Send the request and print the response
        URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/allcalendars/full");

        //URL entryUrl = new URL("http://www.google.com/calendar/feeds/default/calendars/com.google.gdata.data.Link@87c268");

        CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);

        //CalendarEntry calendar= myService.getEntry(entryUrl, CalendarEntry.class);
        //System.out.println("\t" + calendar.getTitle().getPlainText());

        ritorno += "Your calendars:\n";

        for (int i = 0; i < resultFeed.getEntries().size(); i++) {
            CalendarEntry entry = resultFeed.getEntries().get(i);
            ritorno += "\t" + entry.getTitle().getPlainText();
            ritorno += "\t" + entry.getEditLink();
            ritorno += "\t" + entry.getId();
        }

        return ritorno;

    }

    private void createNewCalendar(CalendarService service) throws IOException, ServiceException {
        // Create the calendar
        CalendarEntry calendar = new CalendarEntry();
        calendar.setTitle(new PlainTextConstruct("TestJava"));
        calendar.setSummary(new PlainTextConstruct("This calendar contains the practice schedule and game times."));
        calendar.setTimeZone(new TimeZoneProperty("America/Los_Angeles"));
        calendar.setHidden(HiddenProperty.FALSE);
        calendar.setColor(new ColorProperty("#2952A3"));
        calendar.addLocation(new Where("", "", "Oakland"));

        // Insert the calendar
        URL postUrl = new URL("https://www.google.com/calendar/feeds/default/owncalendars/full");
        CalendarEntry returnedCalendar = service.insert(postUrl, calendar);
        System.out.println("Calendar Inserted");
    }

    private void printAllEvents(CalendarService service, String user)
            throws ServiceException, IOException {
        // Send the request and receive the response:
        URL eventFeedUrl = new URL("https://www.google.com/calendar/feeds/" + user + "/private/full");

        CalendarEventFeed resultFeed = service.getFeed(eventFeedUrl, CalendarEventFeed.class);

        System.out.println("All events on your calendar:");
        System.out.println();
        for (int i = 0; i < resultFeed.getEntries().size(); i++) {
            CalendarEventEntry entry = resultFeed.getEntries().get(i);
            System.out.println("\t" + entry.getTitle().getPlainText());
        }
        System.out.println();
    }

    private void createEvent(CalendarService service, String user) throws IOException, ServiceException {
        //URL postUrl =new URL("https://www.google.com/calendar/feeds/" + user+ "/private/full");

        URL postUrl = new URL("http://www.google.com/calendar/feeds/default/calendars/com.google.gdata.data.Link@87c268");

        CalendarEventEntry myEntry = new CalendarEventEntry();

        myEntry.setTitle(new PlainTextConstruct("Evento da Java"));
        myEntry.setContent(new PlainTextConstruct(
                "Evento creato da classe java."));

        DateTime startTime = DateTime.parseDateTime("2011-11-05T12:00:00-08:00");
        DateTime endTime = DateTime.parseDateTime("2011-11-05T13:00:00-08:00");
        When eventTimes = new When();
        eventTimes.setStartTime(startTime);
        eventTimes.setEndTime(endTime);
        myEntry.addTime(eventTimes);

        // Send the request and receive the response:
        CalendarEventEntry insertedEntry = service.insert(postUrl, myEntry);

        System.out.println("Event Inserted");
    }

    public void createEvent(CalendarService service, String user, DateTime start, DateTime finish) throws IOException, ServiceException {
        //URL postUrl =new URL("https://www.google.com/calendar/feeds/" + user+ "/private/full");

        URL postUrl = new URL("https://www.google.com/calendar/feeds/g4usg76ukrj0rvc8e2clr9u0gk%40group.calendar.google.com/private/full");

        CalendarEventEntry myEntry = new CalendarEventEntry();

        myEntry.setTitle(new PlainTextConstruct("Evento da Java 2"));
        myEntry.setContent(new PlainTextConstruct(
                "Evento creato da classe java."));

        DateTime startTime = start;
        DateTime endTime = finish;
        When eventTimes = new When();
        eventTimes.setStartTime(startTime);
        eventTimes.setEndTime(endTime);
        myEntry.addTime(eventTimes);

        // Send the request and receive the response:
        CalendarEventEntry insertedEntry = service.insert(postUrl, myEntry);

        System.out.println("Event Inserted");
    }

    public String createEvent(CalendarService service, String nameCalendar, String titleEvent, String descEvent, DateTime start, DateTime finish) throws IOException, ServiceException {

        String ritorno = "";



        URL postUrl = new URL(nameCalendar);

        CalendarEventEntry myEntry = new CalendarEventEntry();

        myEntry.setTitle(new PlainTextConstruct(titleEvent));
        myEntry.setContent(new PlainTextConstruct(descEvent));

        DateTime startTime = start;
        DateTime endTime = finish;
        When eventTimes = new When();
        eventTimes.setStartTime(startTime);
        eventTimes.setEndTime(endTime);
        myEntry.addTime(eventTimes);

        // Send the request and receive the response:
        CalendarEventEntry insertedEntry = service.insert(postUrl, myEntry);

        //System.out.println("Event \""+titleEvent+"\" Inserted");
        ritorno = "Event Inserted: " + titleEvent + " from: " + startTime + " ->  to: " + endTime;

        return ritorno;


    }

    public ArrayList<Calendario> getCalendari(CalendarService service, String prefisso) throws IOException, ServiceException {
        ArrayList<Calendario> chiavisti = new ArrayList<Calendario>();

        String urlPre = "https://www.google.com/calendar/feeds/";
        String urlPost = "/private/full";


        URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/allcalendars/full");
        CalendarFeed resultFeed = service.getFeed(feedUrl, CalendarFeed.class);

        for (int i = 0; i < resultFeed.getEntries().size(); i++) {
            CalendarEntry entry = resultFeed.getEntries().get(i);

            String tempName = entry.getTitle().getPlainText();
            String tempCalendar = entry.getId();
            if (tempName.contains(prefisso)) {

                Calendario temp = new Calendario();

                //Creo nome chiavista
                //Tolgo "Turni -"
                tempName = tempName.replace(prefisso, "").trim();
                temp.setName(tempName);


                //Creo URL calendario chiavista
                int last = tempCalendar.lastIndexOf('/');
                tempCalendar = urlPre + tempCalendar.substring(last + 1) + urlPost;

                temp.setCalendar(tempCalendar);

                //System.out.println("\t" + entry.getTitle().getPlainText());
                //System.out.println("\t" + entry.getEditLink());
                //System.out.println("\t" + entry.getId());

                chiavisti.add(temp);
            }
            //System.out.println("\t" + entry.getTitle().getPlainText());
            //System.out.println("\t" + entry.getEditLink());
            //System.out.println("\t" + entry.getId());
        }



        return chiavisti;

    }

    public String createNewCalendarChiavista(CalendarService service, String ownCalendars, String nameCalendar, String descCalendar) throws IOException, ServiceException {
        // Create the calendar
        CalendarEntry calendar = new CalendarEntry();
        calendar.setTitle(new PlainTextConstruct(nameCalendar));
        calendar.setSummary(new PlainTextConstruct(descCalendar));
        //calendar.setTimeZone(new TimeZoneProperty("America/Los_Angeles"));
        calendar.setHidden(HiddenProperty.FALSE);
        //calendar.setColor(new ColorProperty("#2952A3"));
        //calendar.addLocation(new Where("", "", "Oakland"));

        // Insert the calendar
        URL postUrl = new URL(ownCalendars);
        CalendarEntry returnedCalendar = service.insert(postUrl, calendar);
        //System.out.println("Calendar Inserted");

        return "Calendar Inserted: " + nameCalendar;
    }

    public String deleteCalendar(CalendarService service, String ownCalendars, String nameCalendar ) throws MalformedURLException, IOException, ServiceException {
        //boolean deleted = false;
        String ritorno = "Nessun calendario cancellato";
        URL feedUrl = new URL(ownCalendars);
        CalendarFeed resultFeed = service.getFeed(feedUrl, CalendarFeed.class);
        for (int i = 0; i < resultFeed.getEntries().size(); i++) {
            CalendarEntry entry = resultFeed.getEntries().get(i);
            //System.out.println("Deleting calendar: " + entry.getTitle().getPlainText());
            try {
                if (entry.getTitle().getPlainText().trim().equalsIgnoreCase(nameCalendar)){
                      entry.delete();
                      ritorno = "Calendario cancellato:"+nameCalendar;
                      return ritorno;
                }
            } catch (InvalidEntryException e) {
                System.out.println("\tUnable to delete primary calendar");
            }
        }
        return ritorno;
    }

    public String deletePersonalEvent(CalendarService service, String calendar, CalendarEventEntry entry) throws MalformedURLException, IOException, ServiceException{
        String ritorno = "Nessun evento cancallato";

        try{
        URL feedUrl = new URL(calendar);


        CalendarQuery myQuery = new CalendarQuery(feedUrl);
        myQuery.setMinimumStartTime(entry.getTimes().get(0).getStartTime());
        myQuery.setMaximumStartTime(entry.getTimes().get(0).getEndTime());

        // Send the request and receive the response:
        CalendarEventFeed resultFeed = service.query(myQuery, CalendarEventFeed.class);
        List<CalendarEventEntry> entries = resultFeed.getEntries();

        entries.get(0).delete();
        ritorno = "Evento su calendario personale cancellato.";
        return ritorno;
        }
        catch(Exception ex){
            return "Errore di cancellazione su calendario personale!";
        }
        
    }

    public List<CalendarEventEntry> getEventi(CalendarService service, String calendar,DateTime startDate, DateTime endDate) throws MalformedURLException, IOException, ServiceException{

        //URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full");
        URL feedUrl = new URL(calendar);

        CalendarQuery myQuery = new CalendarQuery(feedUrl);
        myQuery.setMinimumStartTime(startDate);
        myQuery.setMaximumStartTime(endDate);


        // Send the request and receive the response:
        CalendarEventFeed resultFeed = service.query(myQuery, CalendarEventFeed.class);
        List<CalendarEventEntry> entries = resultFeed.getEntries();
        //return resultFeed.getEntries().get(0).getTitle().getPlainText();

        //ritorno solo la prima di quelle che trovo

        //if (entries.size()==0) return null;

        //se c'è il pattern che passo negli eventi di quell'ora ritorno solo la prima

        /*
        for (int i = 0; i<entries.size();i++){
            CalendarEventEntry entry = entries.get(i);
            //se il titolo contiene il pattern, lo ritorno!
            if (entry.getTitle().getPlainText().trim().contains(pattern))
                return entry;
        }
        */
        
        // se non esiste quel pattern (ad es "Turno Sala Studio") ritorno null;
        return entries;
        

    }
}
